let request = require('request-promise');
const crypto = require('crypto');
const fs = require('fs-extra')
var mp3Duration = require('mp3-duration');
var AipSpeechClient = require("baidu-aip-sdk").speech;
var APP_ID_BAIDU = "11525645";
var API_KEY_BAIDU = "raHr6rG9S9X8I5ecoXQNL2BV";
var SECRET_KEY_BAIDU = "2LSFLA61SN1o16qGaC092kGA9HBRGiMD";

var baidu_tts_client = new AipSpeechClient(APP_ID_BAIDU, API_KEY_BAIDU, SECRET_KEY_BAIDU);
import { Router } from 'express';
module.exports = app => {
    const config = app.libs.config;
    let appid = "5b46ed72";
    let apikey = "a839b07366a9f438d2b8b6f27fe7b353"
    // let appid = "5b4ebcb6";
    // let apikey = "e99abc4449aa2e67f483c7b0887f3184"
    global.is_playing = false;
    global.last_play_time = new Date();
    let param = {
        "auf": "audio/L16;rate=16000",
        "aue": "lame",
        "voice_name": "xiaoyan",
        "speed": "50",
        "volume": "50",
        "pitch": "50",
        "engine_type": "intp65",
        "text_type": "text"
    };
    let X_Param = new Buffer(JSON.stringify(param)).toString('base64');
    
    let getVoice = async(answer)=>{
        return new Promise((resolve,reject)=>{
            let X_CurTime = Math.floor(new Date().getTime()/1000);
            let X_CheckSum = md5(apikey+X_CurTime+X_Param);
            // let param = {text:encodeURIComponent(answer)}
            // var file = fs.createWriteStream("./1.mp3");
            var options={  
                hostname:'api.xfyun.cn',  
                port:80,  
                uri:`http://api.xfyun.cn/v1/service/v1/tts?text=${encodeURIComponent(answer)}`,
                method:'POST',  
                headers:{
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    'X-Param': X_Param,
                    'X-CurTime': X_CurTime,
                    'X-CheckSum': X_CheckSum,
                    'X-Appid': appid
            }  
            }  
            var filepath = `./static/mp3/${new Date().getTime().toString()}.mp3`;
            var stream = request(options).pipe(fs.createWriteStream(filepath));
            stream.on('finish', () => {
                resolve(filepath);
            });
        })
        
    
        
    };
    let getVoiceFromBaidu = async(answer)=>{
        return new Promise(async (resolve,reject)=>{
            var filepath = `./static/mp3/${new Date().getTime().toString()}.mp3`;
            baidu_tts_client.text2audio(answer,{spd: 5, per: 4}).then(function(result) {
                if (result.data) {
                    fs.writeFileSync(filepath, result.data);
                    resolve(filepath);
                } else {
                    // 服务发生错误
                    console.log(result)
                    reject(result);
                }
            }, function(e) {
                // 发生网络错误
                reject(e);
            });
        })
    };
    let getVoiceDuration = async(filepath)=>{
        return new Promise(async (resolve,reject)=>{
            mp3Duration(filepath, (err, duration) => {
                if (err) {
                    reject(err.message) 
                }else{
                    resolve(duration);
                }
            });
        })
    };
    let md5 = (text) => {
        return crypto.createHash('md5').update(text).digest('hex');
    };
    app.post("/api/bot/voice", async (req, res) => {
        let client_count = app.io.eio.clientsCount;
        if(client_count==0){
            res.json({
                errorCode:"200002",
                errorMessage:"没有socket客户端连接"
            });
            return;
        }
        let message = req.body.message;
        if(!message || !message.trim()){
            res.json({
                errorCode:"200002",
                errorMessage:"内容为空"
            })
            return;
        }
        let need_turing = req.body.need_turing;
        let force_play = req.body.force_play;
        let nickname= req.body.nickname;
        let time_length_message = 0;
        let time_length_answer = 0;
        if(global.is_playing && !force_play){
            console.log("is_playing is true, last_play_time is ",global.last_play_time)
            res.json({
                is_playing:true
            });
            if(new Date() - global.last_play_time>90000){
                global.is_playing = false;
            }
            return;
        }else{
            res.json({
                is_playing:false,
                message:"got an message, ready to play"
            });
            global.is_playing = true;
            global.last_play_time = new Date();
            let answer = "";
            let message_voice_path;
            if(need_turing == "1"){
                // var options = {
                //     hostname:'openapi.tuling123.com',  
                //     uri:`http://openapi.tuling123.com/openapi/api/v2`,
                //     method:'POST',
                //     body: {
                //         "reqType": 0,
                //         "perception": {
                //             "inputText": {
                //                 "text": message
                //             },
                //             "inputImage": {
                //                 "url": "imageUrl"
                //             },
                //             "selfInfo": {
                //                 "location": {
                //                     "city": "北京",
                //                     "province": "北京",
                //                     "street": "白石桥"
                //                 }
                //             }
                //         },
                //         "userInfo": {
                //             "apiKey": "fd1dc424788e46bab2d742c5285e600e",
                //             "userId": "1b7d0a459bc77e13"
                //         }
                //     },
                //     json: true 
                // }
                var options = {
                    hostname:'172.23.11.140',  
                    uri:`http://172.23.11.140:8080/chat`,
                    method:'POST',
                    body: {
                        "query": message
                    },
                    json: true 
                }
                let result = await request(options);
                try{
                    // answer = result.results[0].values.text;
                    answer = result.say;
                    let message_temp = `${nickname}说，${message}`
                    message_voice_path = await getVoiceFromBaidu(message_temp);
                    time_length_message = await getVoiceDuration(message_voice_path);
                }catch(e){
                    global.is_playing = false;
                    return false;
                }
            }else{
                answer = message;
            }
            if(answer.length>100){
                app.io.sockets.emit('m:error', {
                    message:"内容长度太长，不过tts",
                    need_turing:need_turing,
                    answer:answer,
                    filepath:"",
                });
                global.is_playing = false;
                return false;
            }
            let time_length_total = 0;
            let voice_path;
            try{
                voice_path = await getVoiceFromBaidu(answer);
                time_length_answer = await getVoiceDuration(voice_path);
                time_length_total = time_length_answer + 1.5;
            }catch(e){
                global.is_playing = false;
                return false;
            }
            if(time_length_message !=0){
                time_length_total += time_length_message;
                time_length_total += 2//前端2秒问答之间停顿
            }
            setTimeout(()=>{
                global.is_playing = false;
                console.log(`${time_length_total} seconds passed, is_playing is set to false`)
            },time_length_total*1000)
            app.io.sockets.emit('m:answer', {
                message:message,
                need_turing:need_turing,
                answer:answer,
                message_path:message_voice_path,
                filepath:voice_path,
                force_play:force_play,
                is_playing:global.is_playing
            });
        }
    });
    app.post("/api/bot/test",async(req,res)=>{
        
        if(global.is_playing){
            res.json({is_playing:global.is_playing});
        }else{
            res.json({is_playing:global.is_playing});
            global.is_playing = true;
            setTimeout(()=>{
                global.is_playing = false;
            },10000)
        }
        
    })
    app.get("/index",function(req,res,next){
        res.render("index");
    });
    app.get("/index1",function(req,res,next){
        res.render("index1");
    });
}
